#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/7 16:22
# @File    : table_widget.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn
import math
import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Querybox, Messagebox
from tksheet import Sheet
from pandas import DataFrame


class Table(tk.Frame):

    def __init__(self,  *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.data = DataFrame()
        self.current_page = 0
        self.page_size = 10
        self.pages = 1

        self.pack(fill=BOTH, expand=YES)

        self.tab_frame = ttk.Frame(self)
        self.tab_frame.pack(fill=BOTH, padx=2, pady=1, side=TOP)

        self.sheet = Sheet(self.tab_frame,
                           data=[[" " for _ in range(10)] for _ in range(10)])
        self.sheet.enable_bindings()
        self.sheet.pack(fill="both", expand=True)

        #self.page_frame = self.tab_frame
        self.page_frame = ttk.Frame(self)
        self.page_frame.pack(fill=X, side=BOTTOM)


    def init_tab(self, data: DataFrame, page_size=10):
        self.data = data
        self.page_size = page_size
        self.pages = math.ceil(data.shape[0] / page_size)

        # 销毁旧部件
        self.sheet.destroy()
        self.sheet = Sheet(self.tab_frame,
                           show_x_scrollbar=False,
                           show_y_scrollbar=False,
                           show_top_left=False,
                           show_row_index=False,
                           width=500,
                           height=350,
                           row_height=25,
                           column_width=120,
                           align='c',
                           font=("Calibri", 10, "normal"),
                           data=data.iloc[:page_size].values.tolist(),
                           headers=data.columns.tolist())
        #self.sheet.enable_bindings()
        self.sheet.enable_bindings("drag_select", "rc_select")
        #self.sheet.checkbox_column(0, text="1", check_function=lambda x: print("点击"))
        #self.sheet.align_columns(columns=0, align="c")
        # 第0列 居中

        self.sheet.pack(fill=ttk.BOTH, expand=True)
        self.sheet.bind("<Motion>", self.on_mouse_move)

        title = ttk.Button(
            master=self.page_frame,
            text=" 跳转 ",
            command=lambda :self.to_page(int(self.spn.get())-1)
        )
        title.pack(padx=1, pady=1, side=RIGHT)

        self.spn = ttk.Spinbox(self.page_frame, bootstyle="primary", from_=1, to=self.pages)
        self.spn.set(1)
        self.spn.pack(padx=5, pady=2, side=RIGHT)

        title = ttk.Label(
            master=self.page_frame,
            text=f" 共{self.pages}页 /",
            anchor=tk.CENTER
        )
        title.pack(padx=1, pady=1, side=RIGHT)

        title = ttk.Button(
            master=self.page_frame,
            text=" 上一页 ",
            command=self.last_page
        )
        title.pack(padx=5, pady=2, side=RIGHT)

        title = ttk.Button(
            master=self.page_frame,
            text=" 下一页 ",
            command=self.next_page

        )
        title.pack(padx=5, pady=2, side=RIGHT)


    def add_row(self, index, values: tuple):
        pass

    def delete_row(self, index):
        pass

    def next_page(self):
        index = self.page_size*(self.current_page+1)
        index_end = index+self.page_size
        current_data = self.data.iloc[index: index_end]
        if current_data.empty:
            Messagebox.show_warning("最后一页", position=(500, 500))
            return
        self.current_page += 1
        self.spn.set(self.current_page+1)
        self.sheet.set_sheet_data(data=current_data.values.tolist(),
                       reset_col_positions=True,
                       reset_row_positions=True,
                       redraw=True,
                       verify=False,
                       reset_highlights=False)

    def last_page(self):
        print(f"上一页:{self.current_page}")
        if self.current_page-1 == -1:
            Messagebox.show_warning("当前页为首页", position=(500, 500))
            return
        index = self.page_size * (self.current_page - 1)
        index_end = index+self.page_size
        print(f"开始：{index}, 结束：{index_end}")
        current_data = self.data.iloc[index: index_end]
        self.current_page -= 1
        self.spn.set(self.current_page+1)
        self.sheet.set_sheet_data(data=current_data.values.tolist(),
                       reset_col_positions=True,
                       reset_row_positions=True,
                       redraw=True,
                       verify=False,
                       reset_highlights=False)


    def to_page(self, page):
        print(page)
        if page > self.pages-1:
            Messagebox.show_warning("超出最大页数", position=(500, 500))
            return
        self.current_page = page
        self.spn.set(self.current_page+1)
        index = self.page_size * page
        index_end = index+self.page_size
        current_data = self.data.iloc[index: index_end]
        self.sheet.set_sheet_data(data=current_data.values.tolist(),
                       reset_col_positions=True,
                       reset_row_positions=True,
                       redraw=True,
                       verify=False,
                       reset_highlights=False)


    def on_mouse_move(self, event):
        # 获取鼠标在 tksheet 中的位置
        x, y = event.x, event.y
        # print(event.widget)
        # 每个单元格的宽高（这里默认认为每个单元格的宽高都一致）
        if self.sheet.get_row_heights().__len__() <=0: return
        row_wide = self.sheet.get_column_widths()[0]
        row_height = self.sheet.get_row_heights()[0]
        # 计算鼠标当前所在的行（注意要减去表头的高度，如果有的话）
        row, col = y // row_height, x // row_wide
        #print(row, col, row_wide, row_height)
        # 检查行号是否在有效范围内
        if 0 <= row < self.sheet.get_row_heights().__len__():
            # 清除之前所有行的背景颜色
            self.sheet.dehighlight_rows(rows=[], redraw=True)
            # 为当前行加背景颜色
            self.sheet.highlight_rows(rows=[row], bg='#E6EFFD', fg=None)


if __name__ == '__main__':

    #app = ttk.Window("tab")
    app = tk.Tk()

    import numpy as np

    df = DataFrame(np.random.randint(0, 100, (30, 5)))
    df.reset_index(inplace=True)
    df.columns = ["index"]+list("ABCDE")
    Table(app).init_tab(df, 10)

    app.mainloop()
